<template>
  <div class="file-upload">
    <input
      type="file"
      :multiple="multiple"
      @change="handleFileChange"
      ref="fileInput"
    />
    <button @click="uploadFiles">上传文件</button>
    <div v-if="files.length">
      <h3>已选择文件:</h3>
      <ul>
        <li v-for="file in files" :key="file.name">
          {{ file.name }} ({{ formatFileSize(file.size) }})
        </li>
      </ul>
    </div>
    <div v-if="uploadStatus">{{ uploadStatus }}</div>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: "FileUpload",
  props: {
    uploadUrl: {
      type: String,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      files: [],
      uploadStatus: "",
    };
  },
  methods: {
    handleFileChange(event) {
      this.files = Array.from(event.target.files);
    },
    formatFileSize(size) {
      if (size < 1024) return size + " B";
      else if (size < 1024 * 1024) return (size / 1024).toFixed(2) + " KB";
      else return (size / (1024 * 1024)).toFixed(2) + " MB";
    },
    async uploadFiles() {
      if (!this.files.length) {
        this.uploadStatus = "请选择文件后再上传";
        return;
      }

      const formData = new FormData();
      this.files.forEach((file) => formData.append("file", file));

      try {
        this.uploadStatus = "上传中...";
        const response = await request({
          url: this.uploadUrl,
          method: "post",
          data: formData,
        });
        if (response.ok) {
          this.uploadStatus = "上传成功";
          this.files = [];
          this.$refs.fileInput.value = ""; // 重置文件输入
          this.$emit("close");
        } else {
          this.uploadStatus = "上传失败";
        }
      } catch (error) {
        console.error(error);
        this.uploadStatus = "上传出错";
      }
    },
  },
};
</script>

<style scoped>
.file-upload {
  margin: 20px;
}
</style>
